package admin.controllers;

import helpers.PaginatorHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.DealEmailModel;
import models.GeoModel;

import admin.data.DealEmailData;
import admin.data.GeoData;

public class ListDealEmailServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		int page = 1;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		DealEmailData dealEmailData = new DealEmailData();
		dealEmailData.setLimit(20);
		dealEmailData.setPage(page);
		
		ArrayList<DealEmailModel> dealEmails = dealEmailData.list();
		Map<String, GeoModel> cities = new HashMap<String, GeoModel>();
		//Get city
		List<String> ids = new ArrayList<String>();
		for (int i = 0; i < dealEmails.size(); i++) {
			if (!ids.contains(dealEmails.get(i).getCity()) ) {
				ids.add(dealEmails.get(i).getCity());
			}
		}
		
		GeoData geoData = new GeoData();
		cities = geoData.getByManyId(ids);
		
		boolean nextPage = false;
		boolean prevPage = false;
		
		if (dealEmails.size() == dealEmailData.getLimit()) {
			nextPage = true;
		}
		
		if (page > 1) {
			prevPage = true;
		}
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		request.setAttribute("paginator", paginator);
		request.setAttribute("prevPage", prevPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("deals", dealEmails);
		request.setAttribute("page", page);
		request.setAttribute("cities", cities);
		try {
			request.getRequestDispatcher("/admin/pages/list_deal_email.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
}
